package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.bean.ChannelListParam
import com.cheyun.netsalev3.repository.SwitchingDealersRepository
import com.cheyun.netsalev3.utils.MyIntent
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.ForgetActivity
import com.cheyun.netsalev3.view.MainActivity

/**
 * @author Michael
 * @date  2018/12/19 - 17:54.
 */
class SwitchingDealersActivityViewModel(var switchingDealersRepository: SwitchingDealersRepository) : BaseViewModel() {
    var data = MutableLiveData<List<ChannelListParam>>()
    var listdata = ArrayList<ChannelListParam>()
    val channel = MySharedPreferences.getLoginData()?.member?.channel ?: 0

    init {
        switchingDealersRepository.getData(this::setData)
    }

    var networkState = Transformations.switchMap(data) {
        switchingDealersRepository.networkState
    }

    private fun setData(item: List<ChannelListParam>) {
        for (i in item) {
            i.IsSelect = i.channel == channel
        }
        listdata.addAll(item)
        data.postValue(listdata)
    }

    fun onClickItem(view: View, item: ChannelListParam) {
        for (i in listdata) {
            i.IsSelect = i.channel == item.channel
        }

        var moth: () -> Unit = {
            goCrm(view)
        }
        switchingDealersRepository.channelhang(item.channel, moth)
    }

    fun forget(){
        MyApplication.getInstance().getAcitvitys().clear()
        myStartActivity(MyIntent(ForgetActivity::class.java))
    }
    fun goCrm(view: View){
        MyApplication.getInstance().getAcitvitys().clear()
        var intent = Intent(view.context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        view.context.startActivity(intent)
    }

    fun refresh() {
        listdata.clear()
        switchingDealersRepository.getData(this::setData)
    }

}